package com.syq.controller.admin;

import com.alibaba.fastjson.JSON;
import com.syq.entity.User;
import com.syq.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author wgy
 * @version V1.0
 * @project gp12_xiaomi
 * @package ${PACKAGE_NAME}
 * @description: ${TODO}
 * @date 2022/6/28 11:19
 */
@RestController
@WebServlet(name = "GetUserListServlet",urlPatterns = "/getUserList")
public class GetUserListServlet extends HttpServlet {

    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1判断是否登录 admin
        User admin= (User) request.getSession().getAttribute("admin");
        if(admin==null){
            response.sendRedirect(request.getContextPath()+"/admin/login.jsp");
            return;
        }

        //3调用方法
        try {
            List<User> userList=userService.selectAll();
            //4把userList转成JSON字符串
            String json = JSON.toJSONString(userList);
            //5返回
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
